package cn.iocoder.yudao.module.statistics.controller.admin.shareprofit;

import cn.hutool.core.util.NumberUtil;
import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;
import cn.iocoder.yudao.module.statistics.controller.admin.shareprofit.vo.*;
import cn.iocoder.yudao.module.statistics.dal.dataobject.shareprofit.StoreTradeShareProfitDO;
import cn.iocoder.yudao.module.statistics.enums.PartnerStatusEnum;
import cn.iocoder.yudao.module.statistics.service.shareprofit.StoreTradeShareProfitService;
import cn.iocoder.yudao.module.system.api.partner.PartnerApi;
import cn.iocoder.yudao.module.system.api.partner.dto.PartnerRespDTO;
import cn.iocoder.yudao.module.system.enums.partner.PartnerTypeEnum;
import cn.iocoder.yudao.module.trade.api.store.StoreApi;
import cn.iocoder.yudao.module.trade.api.store.dto.StoreRespDTO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;

@Tag(name = "管理后台 - 门店交易合伙人分润")
@RestController
@RequestMapping("/statistics/store-trade-share-profit")
@Validated
public class StoreTradeShareProfitController {

    @Resource
    private StoreTradeShareProfitService storeTradeShareProfitService;

    @Resource
    private PartnerApi partnerApi;

    @Resource
    private StoreApi storeApi;

    @PostMapping("/create")
    @Operation(summary = "创建门店交易合伙人分润")
//    @PreAuthorize("@ss.hasPermission('statistics:store-trade-share-profit:create')")
    public CommonResult<Long> createStoreTradeShareProfit(@Valid @RequestBody StoreTradeShareProfitSaveReqVO createReqVO) {
        return success(storeTradeShareProfitService.createStoreTradeShareProfit(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新门店交易合伙人分润")
//    @PreAuthorize("@ss.hasPermission('statistics:store-trade-share-profit:update')")
    public CommonResult<Boolean> updateStoreTradeShareProfit(@Valid @RequestBody StoreTradeShareProfitSaveReqVO updateReqVO) {
        storeTradeShareProfitService.updateStoreTradeShareProfit(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除门店交易合伙人分润")
    @Parameter(name = "id", description = "编号", required = true)
//    @PreAuthorize("@ss.hasPermission('statistics:store-trade-share-profit:delete')")
    public CommonResult<Boolean> deleteStoreTradeShareProfit(@RequestParam("id") Long id) {
        storeTradeShareProfitService.deleteStoreTradeShareProfit(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得门店交易合伙人分润")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
//    @PreAuthorize("@ss.hasPermission('statistics:store-trade-share-profit:query')")
    public CommonResult<StoreTradeShareProfitRespVO> getStoreTradeShareProfit(@RequestParam("id") Long id) {
        StoreTradeShareProfitDO storeTradeShareProfit = storeTradeShareProfitService.getStoreTradeShareProfit(id);
        return success(BeanUtils.toBean(storeTradeShareProfit, StoreTradeShareProfitRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "合伙人分润明细分页")
//    @PreAuthorize("@ss.hasPermission('statistics:store-trade-share-profit:query')")
    public CommonResult<PageResult<StoreTradeShareProfitRespVO>> getStoreTradeShareProfitPage(@Valid StoreTradeShareProfitPageReqVO pageReqVO) {
        PageResult<StoreTradeShareProfitDO> pageResult = storeTradeShareProfitService.getStoreTradeShareProfitPage(pageReqVO);
        PageResult<StoreTradeShareProfitRespVO> pageResultVO = BeanUtils.toBean(pageResult, StoreTradeShareProfitRespVO.class);
        if (!CollectionUtils.isAnyEmpty(pageResult.getList())) {
            List<Long> storeIds = pageResult.getList().stream().map(StoreTradeShareProfitDO::getStoreId).collect(Collectors.toList());
            List<Long> partnerIds = pageResult.getList().stream().map(StoreTradeShareProfitDO::getPartnerId).collect(Collectors.toList());

            List<StoreRespDTO> storeList = storeApi.getStoreList(storeIds);
            List<PartnerRespDTO> partnerList = partnerApi.getListByIds(partnerIds);

            Map<Long, StoreRespDTO> storeMap = CollectionUtils.isAnyEmpty(storeList)? Collections.emptyMap() :
                    storeList.stream().collect(Collectors.toMap(StoreRespDTO::getId, store -> store));
            Map<Long, PartnerRespDTO> partnerMap = CollectionUtils.isAnyEmpty(partnerList)? Collections.emptyMap() :
                    partnerList.stream().collect(Collectors.toMap(PartnerRespDTO::getId, store -> store));
            pageResultVO.getList().forEach(item -> {
                if (storeMap.containsKey(item.getStoreId())) {
                    item.setStoreStatus(storeMap.get(item.getStoreId()).getStatus());
                    item.setStoreStatusDesc(CommonStatusEnum.getNameByStatus(item.getStoreStatus()));
                }
                if (partnerMap.containsKey(item.getPartnerId())) {
                    PartnerRespDTO partnerTO = partnerMap.get(item.getPartnerId());
                    item.setPartnerName(partnerTO.getName());
                    item.setPhone(partnerTO.getPhone());
                    item.setPartnerStatus(partnerTO.getStatus());
                    item.setPartnerStatusDesc(PartnerStatusEnum.getNameByType(item.getPartnerStatus()));
                }
                item.setPartnerTypeDesc(PartnerTypeEnum.getNameByType(item.getPartnerStatus()));
                item.setOrderPayPrice(item.getOrderPayPrice()-item.getRefundPrice());
                item.setShareProfitPayPrice(item.getShareProfitPayPrice()-item.getShareProfitRefundPrice());
            });
        }
        return success(pageResultVO);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出合伙人分润明细 Excel")
//    @PreAuthorize("@ss.hasPermission('statistics:store-trade-share-profit:export')")
    @OperateLog(type = EXPORT)
    public void exportStoreTradeShareProfitExcel(@Valid StoreTradeShareProfitPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<StoreTradeShareProfitDO> list = storeTradeShareProfitService.getStoreTradeShareProfitPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "门店交易合伙人分润.xls", "数据", StoreTradeShareProfitRespVO.class,
                        BeanUtils.toBean(list, StoreTradeShareProfitRespVO.class));
    }


    @GetMapping("/shareProfit")
    @Operation(summary = "计算分润")
    @Parameter(name = "days", description = "天数", required = true, example = "1")
    public CommonResult<String> shareProfit(@RequestParam("days") Integer days) {
        return success(storeTradeShareProfitService.shareProfit(days));
    }

    @GetMapping("/getByStorePage")
    @Operation(summary = "合伙人分润汇总-按门店分页")
//    @PreAuthorize("@ss.hasPermission('statistics:store-trade-share-profit:getByStorePage')")
    public CommonResult<PageResult<StoreShareProfitVO>> getByStorePage(@Valid StoreShareProfitPageReqVO reqVO) {
        PageResult<StoreShareProfitVO> pageResult = storeTradeShareProfitService.getByStorePage(reqVO);
        pageResult.getList().forEach(item -> {
            item.setStatusDesc(CommonStatusEnum.getNameByStatus(item.getStatus()));
        });
        return success(pageResult);
    }

    @GetMapping("/export-bystore-excel")
    @Operation(summary = "导出合伙人分润汇总-按门店 Excel")
//    @PreAuthorize("@ss.hasPermission('statistics:store-trade-share-profit:export-bystore')")
    @OperateLog(type = EXPORT)
    public void exportStoreTradeShareProfitByStorePageExcel(@Valid StoreShareProfitPageReqVO pageReqVO,
                                                 HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<StoreShareProfitVO> list = storeTradeShareProfitService.getByStorePage(pageReqVO).getList();
        list.stream().forEach(item -> {
            item.setStatusDesc(CommonStatusEnum.getNameByStatus(item.getStatus()));
            item.setOrderPayPriceExport(NumberUtil.div(new BigDecimal(item.getOrderPayPrice()), 100l, 2));
            item.setShareProfitPayPriceExport(NumberUtil.div(new BigDecimal(item.getShareProfitPayPrice()), 100l, 2));
            item.setShareProfitRateExport(NumberUtil.round(item.getShareProfitRate(), 2) + "%");
        });
        // 导出 Excel
        ExcelUtils.write(response, "合伙人分润汇总-按门店.xls", "数据", StoreShareProfitVO.class,
                list);
    }


    @GetMapping("/getByPartnerPage")
    @Operation(summary = "合伙人分润汇总-按合伙人分页")
//    @PreAuthorize("@ss.hasPermission('statistics:store-trade-share-profit:getByPartnerPage')")
    public CommonResult<PageResult<PartnerShareProfitVO>> getByPartnerPage(@Valid StoreShareProfitPageReqVO reqVO) {
        PageResult<PartnerShareProfitVO> pageResult = storeTradeShareProfitService.getByPartnerPage(reqVO);
        return success(pageResult);
    }

    @GetMapping("/export-bypartner-excel")
    @Operation(summary = "导出合伙人分润汇总-按合伙人 Excel")
//    @PreAuthorize("@ss.hasPermission('statistics:store-trade-share-profit:export-bypartner')")
    @OperateLog(type = EXPORT)
    public void exportStoreTradeShareProfitByPartnerPageExcel(@Valid StoreShareProfitPageReqVO pageReqVO,
                                                            HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<PartnerShareProfitVO> list = storeTradeShareProfitService.getByPartnerPage(pageReqVO).getList();
        list.stream().forEach(item -> {
            item.setShareProfitPayPriceExport(NumberUtil.div(new BigDecimal(item.getShareProfitPayPrice()), 100l, 2));
        });
        // 导出 Excel
        ExcelUtils.write(response, "合伙人分润汇总-按合伙人.xls", "数据", PartnerShareProfitVO.class,
                list);
    }

    public static void main(String[] args) {
        BigDecimal big = NumberUtil.div(new BigDecimal(2000l), 100l, 2, RoundingMode.HALF_UP);
        System.out.println(big);
    }

}